<template>
  <Spin :spinning="loading" tip="Loading...">
    <div>
      <!-- table -->
      <BreakSpace label="旧件销毁申请" :containerStyle="{ marginBottom: '10px' }" />
      <FormPanel ref="formPanel" :list="formList" :cols="4" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandle" />
      <BreakSpace label="上传视频/压缩文件" :containerStyle="{ marginBottom: '10px' }" />
      <Spin :spinning="loading" tip="Loading...">
        <UploadFile action-url="/api/file/oss/upload"  :fileTypes="['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'rar', 'zip','mp4','avi','rmvb','WMV','ins','inr']" :fileSize="100" :isOnlyButton="true"  :limit="10000" @change="successHandler">上传附件</UploadFile>
        <FilterTable
          ref="fileTable"
          :columns="columnsFile"
          columnsRef="whbydUploadFile"
          :isSelectColumn="false"
          :onColumnsChange="columnsFile => (this.columnsFile = columnsFile)"
          height=auto
          :dataSource="list"
        />
      </Spin>
      <BreakSpace label="旧件列表" :containerStyle="{ marginBottom: '10px' }" />
      <FilterTable
        ref="table"
        :columns="columns"
        :params="fetchParams"
        :dataSource="dataList"
        :datakey="'records'"
        :onColumnsChange="columns => (this.columns = columns)"
        :onCellChange="onCellChange"
        :isSelectColumn="false"
        height="auto"
        :isPagination="false"
      >
        <!-- <template slot="controls" slot-scope="props">
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">添加</multiuse-button>
      </template> -->
      </FilterTable>
      <div style="padding-top: 3rem"></div>
      <!-- <FormPanel ref="formPanel1" :list="formList1" :cols="1" :formType="'add'" labelWidth="110" :isSubmitBtn="false" @formChange="formChangeHandleFile" /> -->
      <!-- <div style="padding-top: 3rem"></div> -->
      <div
        :style="{
          position: 'fixed',
          left: 0,
          bottom: 0,
          right: 0,
          zIndex: 9,
          borderTop: '1px solid #e9e9e9',
          padding: '10px 20px',
          background: '#fff',
          textAlign: 'right'
        }"
      >
        <multiuse-button type="primary" :click="apply.bind()">上 传</multiuse-button>
        <multiuse-button type="primary" :click="saveDialog.bind()">保 存</multiuse-button>
        <multiuse-button @click="closeDialog">关 闭</multiuse-button>
      </div>
    </div>
  </Spin>
</template>
<script>
import { updateByPtId, applyDestory } from '@/api/usedPartsDestructionDealer/DestructionResultsUpload';
import { getPartType } from '@/api/dictionary';
import moment from 'moment';

export default {
  props: ['editRow'],
  // mixins: [dictionary],
  data() {
    return {
      loading: false,
      dataList: [],
      dataList1: [],
      visible: false,
      visibleDrawer: false,
      collapse: false,
      infoId: null,
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchParams: {}, //ipa 接口
      selectedRows: [], //选中经销商
      formList: this.createFormList(),
      saveData: null,
      activeName: '审核记录',
      saveDataFile: {},
      visibleList: false,
      columnsFile: this.createdTable(),
      list: [],
    };
  },
  async created() {
    this.loading = true;
    await this.assignment();
    this.loading = false;
  },
  mounted() {
    let list = Object.assign([], this.editRow.dtlList);
    list.map(x => {
      x.claimNo = x.cmsClaimNo;
      x.pestructionCount = x.partCount;
      x.partCount = x.claimPartCount;
      x.claimId = x.cmsClaimId;
    });
    this.$refs.table.$refs.pageTable.EXECUTE_INSERT(list);
    this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(this.editRow.fileList2);
    this.onCellChange();
  },
  methods: {
    async assignment() {
      let res = await getPartType({ type: 5531 });
      for (let row in this.editRow) {
        this.formList.map(x => {
          // if (row == 'fileList2' && x.fieldName == 'wayFiles') {
          //   x.initialValue = this.editRow.fileList2.map(f => ({ name: f.title, url: f.fileUrl }));
          // }
          if (x.fieldName == 'destoryStatus') {
            x.initialValue = res.data.find(x => x.codeId == this.editRow.destoryStatus).codeCnDesc;
          }
          if (x.fieldName == row) {
            x.initialValue = this.editRow[row];
          }
        });
      }
    },
    delVideo(val){
      console.log("#@!#!",val)
      this.$refs.fileTable.$refs.pageTable.EXECUTE_DELETE([val]);
    },
    // 上传成功回调
    successHandler(val) {
      if(val == 1){
        this.loading = true;
      }else{
        this.loading = false;
        if (val&&val.length>0) {
          if (val[0].url.errorList&&val[0].url.errorList.length>0) {
            this.errorList = val[0].url.errorList;
          }else{
            let json = JSON.parse(JSON.stringify(val));
            let data = {};
            data.createdAt = moment().format('YYYY-MM-DD HH:mm:ss');
            data.title = json[json.length - 1].name;
            data.fileUrl = json[json.length - 1].url;
            this.$refs.fileTable.$refs.pageTable.EXECUTE_INSERT(data);
          }
        }else{
          this.errorList = []
        }
      }
    },
    onCellChange(columns, row) {
      let sum = 0;
      this.$refs.table.$refs.pageTable.list.map(x => {
        console.log(x);
        sum += Number(x.pestructionCount);
      });
      this.formList.find(x => x.fieldName == 'destoryCountSS').initialValue = sum;
      // this.formList.find(x => x.fieldName == 'cmsClaimCount').initialValue = this.$refs.table.$refs.pageTable.list.length;
    },
    add() {
      this.visibleList = true;
    },
    closeAdd() {
      this.visibleList = false;
    },
    saveAdd(val) {
      this.visibleList = false;
      let list = Object.assign([], val);
      let pageList = this.$refs.table.$refs.pageTable.list;
      val.map(x => {
        if (pageList.find(f => f.claimId != x.claimId)) {
          list.push(x);
        }
      });
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE(this.$refs.table.$refs.pageTable.list);
      this.$refs.table.$refs.pageTable.EXECUTE_INSERT(list);
      this.formList.find(x => x.fieldName == 'cmsClaimCount').initialValue = this.$refs.table.$refs.pageTable.list.length;
      let num = 0;
      this.$refs.table.$refs.pageTable.list.map(x => {
        num += Number(x.pestructionCount || 0);
      });
      this.formList.find(x => x.fieldName == 'destoryCount').initialValue = num;
    },
    formChangeHandle(val) {
      this.saveData = val;
    },
    formChangeHandleFile(val) {
      this.saveDataFile = val;
    },
    //搜索获取数据
    changeHandle(val) {
      this.fetchParams = val;
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    deleteHandle(row) {
      this.$refs.table.$refs.pageTable.EXECUTE_DELETE([row]);
    },
    //保存
    async saveDialog() {
      this.$refs.formPanel.SUBMIT_FORM();
      let list = this.$refs.table.$refs.pageTable.list;
      let fileList = [];
      if (this.saveData && list.length) {
        let save = Object.assign({}, this.saveData);
        // if (!list.find((x) => Number(x.pestructionCount) < 0) && list.find((x) => Number(x.pestructionCount) > x.partCount)) {
        //   this.$notify({
        //     title: '警告',
        //     message: '请输入正确的销毁数量!',
        //     type: 'warning',
        //   });
        //   return false;
        // }
        list.map(x => {
          x.cmsClaimId = x.claimId;
          x.cmsClaimNo = x.claimNo;
          let partCount = x.partCount;
          x.partCount = x.pestructionCount;
          x.claimPartCount = partCount;
        });

        this.$refs.fileTable.$refs.pageTable.list.map(x => {
          delete x.fileId
          fileList.push(x);
        });

        this.editRow.dtlList = list;
        this.editRow.fileList = fileList;
        this.editRow.destoryStatus = 55311006;

        this.loading = true;
        let res = await updateByPtId(this.editRow);
        if (res.resultCode == 200) {
          this.$emit('save');
          return this.$notify.success({ title: '提示信息', message: '保存成功' });
        } else {
          this.loading = false;
        }
      }
    },
    async apply() {
      this.$refs.formPanel.SUBMIT_FORM();
      let list = this.$refs.table.$refs.pageTable.list;
      let fileList = [];
      if (this.saveData && list.length) {
        let save = Object.assign({}, this.saveData);
        // if (!list.find((x) => Number(x.pestructionCount) < 0) && list.find((x) => Number(x.pestructionCount) >= x.partCount)) {
        //   this.$notify({
        //     title: '警告',
        //     message: '请输入正确的销毁数量!',
        //     type: 'warning',
        //   });
        //   return false;
        // }
        list.map(x => {
          x.cmsClaimId = x.claimId;
          x.cmsClaimNo = x.claimNo;
          let partCount = x.partCount;
          x.partCount = x.pestructionCount;
          x.claimPartCount = partCount;
        });
        this.$refs.fileTable.$refs.pageTable.list.map(x => {
          delete x.fileId
          fileList.push(x);
        });

        this.editRow.dtlList = list;
        this.editRow.fileList = fileList;
        this.editRow.destoryStatus = 55311007;

        this.loading = true;
        let res = await updateByPtId(this.editRow);
        if (res.resultCode == 200) {
          this.$emit('save');
          return this.$notify.success({ title: '提示信息', message: '上传成功' });
        } else {
          this.loading = false;
        }
        this.loading = false;
      }
    },
    //取消操作
    closeDialog() {
      this.$emit('close');
    },
    chooseOrderNo() {
      this.visible = true;
    },
    createFormList() {
      return [
        {
          type: 'INPUT',
          label: '销毁单号',
          fieldName: 'destoryNo',
          placeholder: '',
          readonly: true,
          initialValue: '',
          disabled: true // 置灰
        },
        {
          type: 'INPUT',
          label: '旧件数量',
          fieldName: 'destoryCountSS',
          placeholder: '',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'INPUT',
          label: '旧件状态',
          fieldName: 'destoryStatus',
          placeholder: '请输入操作人...',
          readonly: true,
          disabled: true, // 置灰
          initialValue: ''
        },
        {
          type: 'DATE',
          label: '销毁日期',
          fieldName: 'destoryDate',
          placeholder: '请选择日期...',
          valueFormat: 'yyyy-MM-dd', //返回数据格式
          disabled: true,
          initialValue: ''
        },
        {
          type: 'TEXT_AREA',
          label: '备注',
          fieldName: 'remarks',
          placeholder: '备注',
          rows: 3,
          selfCols: 4, // 元素占据几行
          initialValue: '',
          disabled: true
        },
        // {
        //   type: 'UPLOAD_FILE',
        //   label: '上传附件',
        //   fieldName: 'wayFiles',
        //   placeholder: '上传附件...',
        //   initialValue: [],
        //   rules: [{ required: true, message: '请上传附件', trigger: 'blur' }],
        //   upload: {
        //     actionUrl: '/api/file/oss/upload',
        //     limit: 100,
        //     tipText: '支持PDF、RAR、JPG格式'
        //   }
        // }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          fixed: 'left',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 90,
          render: (props, h) => {
            return (
              <div>
                <el-button size="mini" type="text" onClick={() => this.delVideo(props.row)}>
                  删除
                </el-button>
              </div>
            );
          }
        },
        {
          title: '附件标题',
          dataIndex: 'title',
          showOverflowTooltip: true,
          render: p => {
            return (
              <a style="color:#bb0a30" href={p.row.fileUrl} target="_blank" download={p.row.title}>
                {p.row.title}
              </a>
            );
          }
        },
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        { title: '索赔单号', dataIndex: 'claimNo', sorter: true },
        { title: '索赔类型', dataIndex: 'cmsClaimTypeStr', sorter: true },
        { title: 'VIN', dataIndex: 'vin', sorter: true },
        { title: '是否回运', dataIndex: 'ifReturnStr', sorter: true },
        { title: '旧件代码', dataIndex: 'partCode', sorter: true },
        { title: '旧件名称', dataIndex: 'partName', sorter: true },
        { title: '数量', dataIndex: 'partCount', sorter: true },
        { title: '销毁数量', dataIndex: 'pestructionCount', sorter: true },
        { title: '销毁说明', dataIndex: 'partRemarks', sorter: true }
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
